import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/company_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';

class ChangeCompanyController extends GetxController {
  MultiState multiState = MultiState.loading;
  List<CompanyEntity> companyList = [];

  @override
  void onReady() {
    super.onReady();
    getCompanyList();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getCompanyList();
  }

  Future<void> getCompanyList() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_COMPANY_LIST,
      {},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          multiState = MultiState.fail;
          update();
          return;
        }
        if (data is List) {
          companyList = data.map((element) {
            return CompanyEntity().fromJson((element as Map<String, dynamic>));
          }).toList();
          multiState = companyList.isNotEmpty ? MultiState.success : MultiState.empty;
          update();
        }
      },
      onFail: (code, msg) {
        multiState = MultiState.fail;
        update();
      },
      onError: (msg) {
        multiState = MultiState.error;
        update();
      },
    );
  }

  Future<void> searchCompany() async {
    if (companyList.isNotEmpty) {
      dynamic data = await Get.toNamed(Routes.searchCompany, arguments: companyList);
      if (data != null && data is Map) {
        String companyId = data[Constant.PARAM_COMPANY_ID];
        String companyName = data[Constant.PARAM_COMPANY_NAME];
        backResult(companyId, companyName);
      }
    }
  }

  void backResult(String companyId, String companyName) {
    if (companyId.isEmpty) {
      ToastUtils.toast("公司id为空");
      return;
    }
    Get.back(result: {
      Constant.PARAM_COMPANY_ID: companyId,
      Constant.PARAM_COMPANY_NAME: companyName,
    });
  }
}
